package com.chat.netty.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * TextWebSocketFrame是websocket转为用于处理文本的对象
 */
@Component
@Scope("prototype")
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 用于记录和管理所有客户端的channle,可以用于转发
     */
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

//    @Autowired
//    private RedisTemplate redisTemplate;

    /**
     * 将本channel添加到channels
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    /**
     * 消息处理
     *
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
        String content = msg.text();
        System.out.println(channelHandlerContext.channel().remoteAddress() + "\n" + channelHandlerContext.channel().id());
        // 分发消息
        clients.writeAndFlush(
                new TextWebSocketFrame(content+"---"+DateUtil.now())
        );
//        List<String> strings = new ArrayList<>();
//        strings.add(content);
//        strings.add(DateUtil.now());
//        String key = "content " + UUID.randomUUID() + " " + DateUtil.now();
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.opsForValue().set(key, strings);
//        System.out.println(redisTemplate.opsForValue().get(key));
//        Set<String> keys = redisTemplate.keys("content" + "*");
//        for (String key2 : keys){
//            System.out.println(redisTemplate.opsForValue().get(key2));
//        }
    }

    /**
     * channel断开
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 当触发handlerRemoved，ChannelGroup会自动移除对应客户端的channel
//        clients.remove(ctx.channel());
        System.out.println("客户端断开，channle对应的长id为："
                + ctx.channel().id().asLongText());
        System.out.println("客户端断开，channle对应的短id为："
                + ctx.channel().id().asShortText());
    }

}
